package cn.melonlib.authentication.comp.filter;

import cn.melonlib.cores.graphql.comp.web.anno.GraphqlApi;
import cn.melonlib.cores.graphql.comp.web.bean.GraphqlArguments;
import cn.melonlib.cores.graphql.comp.web.utils.GraphqlArgumentsUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.DispatcherType;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

@Component
public class CookieAuthenticationInterceptor implements HandlerInterceptor {


    @Resource
    private GraphqlArgumentsUtils graphqlArgumentsUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getDispatcherType() == DispatcherType.ASYNC) {
            //避免异步请求多次拦截带来的额外开销
            return true;
        }
        String method=request.getMethod();
        //排出掉一些非正常认证的拦截
        if(!List.of("POST","GET").contains(method)){
            return true;
        }
        if (handler instanceof HandlerMethod handlerMethod && Objects.nonNull(AnnotationUtils.findAnnotation(handlerMethod.getMethod(), GraphqlApi.class))) {
            graphqlArgumentsUtils.init(request);
            GraphqlArguments arguments=graphqlArgumentsUtils.getArguments();
            String query=arguments.getQuery().replaceAll("\\s"," ");
            if(query.contains("IntrospectionQuery")){
                return true;
            }
        }
        return true;
    }
}
